package vip.wangwenhao.common.result;

import lombok.Data;
import vip.wangwenhao.common.util.BeanUtils;
import vip.wangwenhao.common.enums.ResultCode;

import java.util.Map;

/**
 * 接口返回数据结构规范
 *
 * @param <T>
 * @author wangwenhao
 */
@Data
public class Result<T> {

    private String code;
    private String message;
    private T data;
    private Boolean success;

    public Boolean isSuccess(){
        return this.success;
    }

    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setSuccess(Boolean.TRUE);
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMessage(ResultCode.SUCCESS.getMessage());
        result.setData(data);
        return result;
    }

    public static <T> Result<T> fail(ResultCode resultCode) {
        Result<T> result = new Result<>();
        result.setSuccess(Boolean.FALSE);
        result.setCode(resultCode.getCode());
        result.setMessage(resultCode.getMessage());
        result.setData(null);
        return result;
    }

    public static Map<String, Object> failToMap(ResultCode resultCode) {
        Result<Object> result = Result.fail(resultCode);
        return BeanUtils.beanToMap(result);
    }

    public static Map<String, Object> failToMap(ResultCode resultCode, String message) {
        Result<Object> result = Result.fail(resultCode, message);
        return BeanUtils.beanToMap(result);
    }

    public static <T> Result<T> fail(ResultCode resultCode, String message) {
        Result<T> result = new Result<>();
        result.setSuccess(Boolean.FALSE);
        result.setCode(resultCode.getCode());
        result.setMessage(message == null ? resultCode.getMessage() : message);
        result.setData(null);
        return result;
    }
}